"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig")
const SystemErrException = require("../../exception/systemError");
const LogicErrException = require("../../exception/logicError");

class RoleService extends Service {

  async addRole(roleMenusObj) {
    try {
      const { ctx } = this;
      const { currentUserId } = ctx;
      let { nameKey, name, remark } = roleMenusObj
      // 判断新增角色名称是否已经存在
      let isSingle = await this.ctx.model.Sys.Role.findAll({
        where: {
          name
        }
      })

      if (isSingle.length != 0) {
        return {
          code: httpCode.LOGICERROR,
          message: "角色名称已存在！"
        }
      }

      // 创建role
      const roleResult = await ctx.model.Sys.Role.create({
        name,
        nameKey,
        remark,
        userId: currentUserId
      });
      // 创建关联关系
      const roleMens = roleMenusObj.checkedKeys.map(item => {
        return {
          roleId: roleResult.id,
          menuId: item
        }
      })
      await ctx.model.Sys.RoleMenu.bulkCreate(roleMens);
      return {
        code: httpCode.SUCCESS,
        message: "角色添加成功"
      }
    } catch (error) {
      this.ctx.logger.info(error);
    }
  }

  async getRoles() {
    try {
      const { ctx } = this;
      let { currentUserId } = ctx;

      let roles = await ctx.model.Sys.Role.findAll({
        where: {
          userId: currentUserId,
        },
        order: [['update_date', 'asc']], // 排序规则
      });
      return {
        data: roles,
        code: httpCode.SUCCESS,
        message: '角色查询成功！'
      }
    } catch (error) {
      throw new SystemErrException("角色查询异常：" + error);
    }
  }

  // 获取角色信息，以及角色相关的权限
  async getRole(id) {
    try {
      const { ctx, app } = this;
      // 获取角色信息
      const role = await ctx.model.Sys.Role.findByPk(id);
      // 获取菜单信息
      const allMenus = await ctx.model.Sys.Role.findAll({
        where: { id },
        include: {
          model: app.model.Sys.Menu
        }
      })
      // 获取选中菜单叶子节点id
      const menus = JSON.parse(JSON.stringify(allMenus))[0].SMenus;
      let checkedMenusIds = [];
      // 返回菜单树，我们这里只需要叶子节点的id
      (function makeTreeData(arr, parentId) {
        let temp = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].parentId === parentId) {
            let menu = JSON.parse(JSON.stringify(arr[i]));
            temp.push(menu)
            let childMenu = makeTreeData(menus, menu.id);
            if (childMenu.length > 0) {
              menu.children = childMenu;
            } else {
              checkedMenusIds.push(menu.id);
            }
          }
        }
        return temp
      })(menus, null);

      const result = {
        id,
        name: role.name,
        checkedMenusIds
      }
      return {
        data: result,
        code: httpCode.SUCCESS,
        message: '成功获取角色信息'
      }
    } catch (error) {
      throw new SystemErrException("获取角色信息异常：" + error);
    }
  }

  async updateRole(roleMenusObj) {
    let transaction;
    try {
      const { ctx } = this;
      transaction = await this.ctx.model.transaction();
      let { id, nameKey, name, remark, checkedKeys } = roleMenusObj;
      // 更新角色
      await ctx.model.Sys.Role.update({
        nameKey, name, remark
      }, {
        where: { id }
      })
      // 删除之前的用户角色表数据  
      await ctx.model.Sys.RoleMenu.destroy({
        where: { role_id: id }
      })
      // 创建新的连接
      const roleMens = roleMenusObj.checkedKeys.map(item => {
        return {
          roleId: id,
          menuId: item
        }
      })
      await ctx.model.Sys.RoleMenu.bulkCreate(roleMens);
      await transaction.commit();
      // 判断结果
      return {
        code: httpCode.SUCCESS,
        message: '更新成功！'
      }
    } catch (error) {
      this.ctx.logger.error(error);
      await transaction.rollback();
    }
  }

  async deleteRole(id) {
    let transaction;
    try {
      const { ctx } = this;
      transaction = await this.ctx.model.transaction();
      await ctx.model.Sys.Role.destroy({
        where: { id }
      })

      await ctx.model.Sys.RoleMenu.destroy({
        where: { role_id: id }
      })

      await transaction.commit();
      return {
        code: httpCode.SUCCESS,
        message: '删除成功！'
      }
    } catch (error) {
      throw new SystemErrException("角色菜单删除异常：" + error);
    }
  }

}

module.exports = RoleService;
